package com.honey.solr.entity.method;

import java.util.ArrayList;
import java.util.List;

import com.honey.compilation.java.Clazz;
import com.honey.compilation.java.ElseBlock;
import com.honey.compilation.java.IfBlock;
import com.honey.compilation.java.Method;
import com.honey.compilation.java.Parameter;
import com.honey.core.calculator.JavaNameCalculator;
import com.honey.core.utils.JavaBeansUtil;
import com.honey.solr.SchemaField;
import com.honey.solr.SolrFactory;
import com.honey.solr.SolrPlugin;

public class SetterAndGetterMethod {
	
	private SolrFactory solrFactory = null;
	private Clazz clazz = null ;
	public SetterAndGetterMethod( SolrFactory solrFactory, Clazz clazz ){
		this.solrFactory =  solrFactory;
		this.clazz =  clazz;
	}
	
	public List<Method> createMethod(){
		List<Method> answer = new ArrayList<Method>();
		List<SchemaField> list = solrFactory.getSchemaFields();
		JavaNameCalculator c = solrFactory.getJavaNameCalculator();
		SolrPlugin sp = solrFactory.getSolrPlugin();
		boolean isFinal = sp.isTargetEntityFinalMethod();
		boolean returnThis = sp.isTargetEntitySetterReturnThis();
		boolean trimStrings = sp.isTargetEntityTrim();
		for(SchemaField sf : list ){
			String name = c.fieldNameCalculator(sf.getName());
			Method method = new Method(JavaBeansUtil.getSetterMethodName(name));
			method.addParameter(
					new Parameter(sf.getType(),name)
			);
			method.getDecoration().setFinal(isFinal);
			if(sf.getType().isString() && trimStrings){
				IfBlock ifblock = new IfBlock(name+" != null");
				ifblock.addBodyLine("this." +name+" = "+name+".trim()" );
				method.addBlocks(ifblock);
				ElseBlock elseblock = new ElseBlock();
				elseblock.addBodyLine("this." +name+" = null" );
				method.addBlocks(elseblock);
			}else{
				method.addBodyLine("this." +name+" = "+name );
			}
			if(returnThis){
				method.setReturnType(clazz.getType());
				method.addBodyLine("return this" );
			}
			answer.add(method);
			method = new Method(JavaBeansUtil.getGetterMethodName(name, sf.getType()));
			method.setReturnType(sf.getType());
			method.getDecoration().setFinal(isFinal);
			method.addBodyLine("return this." +name);
			answer.add(method);
		}
		return answer;
	}
}
